package com.itheima.util;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;

public class EmailUtil {
    // 邮箱相关配置
    private static final String SMTP_HOST = "smtp.qq.com";  // QQ SMTP 服务器
    private static final String SMTP_PORT = "587";          // SMTP端口
    private static final String FROM_EMAIL = "2171708754@qq.com"; // 发送邮件的QQ邮箱
    private static final String AUTH_CODE = "flzqayyqcgmpeaef"; // QQ邮箱的授权码

    /**
     * 发送验证码到指定邮箱
     */
    public static boolean sendVerificationCode(String toEmail, String code) {
        Properties properties = new Properties();
        properties.put("mail.smtp.host", SMTP_HOST);
        properties.put("mail.smtp.port", SMTP_PORT);
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");

        // 设置邮件会话
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM_EMAIL, AUTH_CODE);
            }
        });

        try {
            // 创建邮件
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(FROM_EMAIL));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
            message.setSubject("验证码");

            // 邮件正文内容
            message.setText("您的验证码是：" + code);

            // 发送邮件
            Transport.send(message);
            System.out.println("验证码已发送至邮箱：" + toEmail);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return false;
    }
}
